
public class No018 {

    public static class ListNode {
        int val;
        ListNode next = null;

        @Override
        public String toString() {
            return "ListNode{" +
                    "val=" + val +
                    ", next=" + next +
                    '}';
        }

        ListNode(int val) {
            this.val = val;
        }
    }

    /**
     * 给定单向链表的头指针和一个节点，定义一个函数在O(1)时间内删除该节点。
     */
    public void DeleteNode(ListNode pHead, ListNode pToBeDeleted) {
        if (pHead == null || pToBeDeleted == null ) return;
        // 要删除的节点不是尾节点
        if (pToBeDeleted.next != null) {
            pToBeDeleted.val = pToBeDeleted.next.val;
            pToBeDeleted.next = pToBeDeleted.next.next;
        }
        // 只有一个节点
        else if (pHead == pToBeDeleted) {
            pHead = null;
        }
        // 删除尾节点
        else {
            ListNode node = pHead;
            while (node.next != pToBeDeleted){
                node = node.next;
            }
            node.next = null;
        }
    }

    /**
     * 在一个排序的链表中，存在重复的结点，
     * 请删除该链表中重复的结点，重复的结点不保留，返回链表头指针。
     * 例如，链表1->2->3->3->4->4->5 处理后为 1->2->5
     */

    public static ListNode deleteDuplication(ListNode pHead) {
        if (pHead == null || pHead.next == null) {
            return pHead;
        }
        // 自己构建辅助头结点
        ListNode head = new ListNode(0);
        head.next = pHead;
        ListNode pre = head;
        ListNode cur = head.next;
        while (cur != null) {
            if (cur.next != null && cur.next.val == cur.val) {
                // 相同结点一直前进
                while (cur.next != null && cur.next.val == cur.val) {
                    cur = cur.next;
                }
                // 退出循环时，cur 指向重复值，也需要删除，而 cur.next 指向第一个不重复的值
                // cur 继续前进
                cur = cur.next;
                // pre 连接新结点
                pre.next = cur;
            } else {
                pre = cur;
                cur = cur.next;
            }
        }
        return head.next;
    }

    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(1);
        ListNode node3 = new ListNode(2);
        ListNode node4 = new ListNode(3);
        ListNode node5 = new ListNode(3);
        ListNode node6 = new ListNode(4);
        ListNode node7 = new ListNode(4);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        node5.next = node6;
        node6.next = node7;
        System.out.println(node1);
        System.out.println(deleteDuplication(node1));

    }

}
